/**
 *
 */
package com.pocketsweet.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.R;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author bobhu
 */
@ContentView(R.layout.activity_register_2)
public class VerifySmsCode extends Activity {

    @ViewInject(R.id.btn_sms_retry)
    private TextView btnSmsRetry;

    @ViewInject(R.id.etSmsCode)
    private EditText etSmsCode;

    @ViewInject(R.id.mainHeader)
    private HeaderLayout header;
    private long mExitTime = 0;// 退出事件用到的事件

    private LoadingDailog mLoadingDialog;
    private Timer timer;
    private final int TIMERMSG = 0x01;
    private int time = 60;
    private boolean getted = true;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIMERMSG:
                    if (time != 0) {
                        time--;
                        btnSmsRetry.setText(time + "s后再次获取");
                    } else if (time == 0) {
                        timer.cancel();
                        getted = false;
                        btnSmsRetry.setText("获取验证码");
                        time = 60;
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        mLoadingDialog = ToolKits.createLoadingDialog(this, "验证中...");
        mLoadingDialog.setText("加载中");
        setHeaderFunction();
        Intent intent = getIntent();
        String needReVerify = intent.getStringExtra("needReVerify");
        String phone = intent.getStringExtra("phone");
        if (needReVerify == null)
            needReVerify = " ";
        if (needReVerify.equals("true")) {
            // 如果你的账号需要重新发送短信请参考下面的代码
            MLUser.requestMobilePhoneVerifyInBackground(phone,
                    new RequestMobileCodeCallback() {
                        @Override
                        public void done(AVException e) {
                            // 发送了验证码以后做点什么呢
                            if (e != null) {
                                ToolKits.toast(VerifySmsCode.this,
                                        "" + e.getCode());
                                ToolKits.toast(VerifySmsCode.this,
                                        e.getMessage());
                                return;
                            }
                            ToolKits.toast(VerifySmsCode.this,
                                    R.string.sms_code_resend);
                        }
                    });
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                Message message = new Message();
                message.what = TIMERMSG;
                handler.sendMessage(message);
            }
        }, 0, 1000);
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setRightText("下一步");
        header.setMiddleText("注册");
        header.setRighttContainerClickListener(new onRightContainerListener() {
            @Override
            public void onClick() {
                String smsCode = etSmsCode.getText().toString();
                if (TextUtils.isEmpty(smsCode)) {
                    ToolKits.toast(VerifySmsCode.this, R.string.sms_code_empty);
                    return;
                }

                mLoadingDialog.show();
                MLUser.verifyMobilePhoneInBackground(smsCode,
                        new AVMobilePhoneVerifyCallback() {

                            @Override
                            public void done(AVException e) {
                                mLoadingDialog.dismiss();
                                if (e != null) {
                                    ToolKits.toast(VerifySmsCode.this,
                                            e.getCode() + e.getMessage());
                                    return;
                                }
                                // 验证通过进入下一个页面
                                timer.cancel();
                                Intent infoInent = new Intent(
                                        VerifySmsCode.this,
                                        CreateUserInfo.class);
                                VerifySmsCode.this.startActivity(infoInent);
                            }
                        });

            }
        });
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                Intent intent = new Intent(VerifySmsCode.this, Register.class);
                VerifySmsCode.this.startActivity(intent);
            }
        });
    }

    @OnClick(R.id.btn_sms_retry)
    public void onSmsRetryClick(View view) {
        if (getted == true) {
            return;
        }
        String phone = "";
        if (UserService.getCurrentUser() == null || UserService.getCurrentUser().getMobilePhoneNumber() == null) {
            phone = getIntent().getStringExtra("phone");
            if (StringUtils.isEmpty(phone) || phone == null) {
                return;
            }
        } else {
            phone = UserService.getCurrentUser().getMobilePhoneNumber();
        }
        getted = true;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                Message message = new Message();
                message.what = TIMERMSG;
                handler.sendMessage(message);
            }
        }, 0, 1000);

        // 如果你的账号需要重新发送短信请参考下面的代码
        MLUser.requestMobilePhoneVerifyInBackground(
                phone, new RequestMobileCodeCallback() {
                    @Override
                    public void done(AVException e) {
                        // 发送了验证码以后做点什么呢
                        if (e != null) {
                            ToolKits.toast(VerifySmsCode.this, "发送失败" + e.getCode());
//                            ToolKits.toast(VerifySmsCode.this, "" + e.getCode());
//                            ToolKits.toast(VerifySmsCode.this, e.getMessage());
                            return;
                        } else {
                            ToolKits.toast(VerifySmsCode.this,
                                    R.string.sms_code_resend);
                        }
                    }
                });
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlet();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitAlet() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast toast = Toast.makeText(VerifySmsCode.this, "再按一次退出程序",
                    Toast.LENGTH_LONG);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.BOTTOM, 0, 150);
            toast.show();
            mExitTime = System.currentTimeMillis();

        } else {
            VerifySmsCode.this.finish();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}
